package com.zzyl.nursing.controller.member;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.core.controller.BaseController;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.thread.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.service.MemberReservationService;
import com.zzyl.nursing.vo.CountVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * 预约信息Controller
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/member/reservation")
@Api(tags = "预约信息相关接口")
public class MemberReservationController extends BaseController {
    @Autowired
    private MemberReservationService memberReservationService;

    /**
     * 查询取消预约数量(status:0待报到,1已完成,2取消,3过期)
     * 根据userid和时间段
     */
    @GetMapping("/cancelled-count")
    @ApiOperation("查询取消预约数量")
    public R<Integer> getCancelledCount() {
        Long userId = UserThreadLocal.getUserId();
        long now = System.currentTimeMillis();
        LocalDateTime ldtNow = LocalDateTimeUtil.of(now);
        LocalDateTime startOfDay = ldtNow.toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1);

        int count = memberReservationService.getCancelledCount(userId, startOfDay, endOfDay);
        return R.ok(count);
    }

    /**
     * 查询每个时间段剩余预约次数
     * param time 时间的毫秒值
     */
    @GetMapping("/countByTime")
    @ApiOperation("查询每个时间段剩余预约次数")
    public R<List<CountVo>> getCountByTime(Long time) {
        // 毫秒值转ldt
        LocalDateTime startOfDay = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
        LocalDateTime endOfDay = startOfDay.plusDays(1);
        List<CountVo> result = memberReservationService.getCountByTime(startOfDay,endOfDay);
        return R.ok(result);
    }

    @PostMapping
    @ApiOperation("新增预约")
    public AjaxResult add(@RequestBody ReservationDto dto) {
        memberReservationService.add(dto);
        return AjaxResult.success();
    }

    @GetMapping("/page")
    @ApiOperation("分页查询预约信息")
    public R<TableDataInfo<List<Reservation>>> page(Integer pageNum, Integer pageSize, Integer status) {
        startPage();
        List<Reservation> result = memberReservationService.page(status);
        return R.ok(getDataTable(result));
    }

    @PutMapping("/{id}/cancel")
    @ApiOperation("取消预约")
    public AjaxResult cancel(@PathVariable Long id) {
        memberReservationService.cancel(id);
        return AjaxResult.success();
    }

}